﻿Imports KOR.Helpers.Data
Imports KOR.Helpers
Imports KOR.Support.Client
Imports System.Web

Public Module Core

    Dim _dda As DirectDataAccess
    Public ReadOnly Property DDA As DirectDataAccess
        Get
            If _dda Is Nothing Then _dda = New DirectDataAccess("strConnection")

            Return _dda
        End Get
    End Property

    Dim _cutofdate As Date?
    Public ReadOnly Property CutOffDate As Date
        Get
            _cutofdate = CDate(ValueOrDefault(GetAppSetting("InventoryCutOffDate"), Nothing))
            Return _cutofdate
        End Get
    End Property

    Public ReadOnly Property UserID As Integer
        Get
            If Not HttpContext.Current.Items.Contains("UserID") Then
                If HttpContext.Current.User IsNot Nothing Then HttpContext.Current.Items("UserID") = BL.Users.GetUserIDByUsername(HttpContext.Current.User.Identity.Name)
            End If
            Return CInt(ValueOrDefault(HttpContext.Current.Items("UserID"), 0))
        End Get
    End Property


    Public Function LastSyncTime(tableName As String, Optional columnName As String = "LastSyncTime") As Date
        Dim sql As String = "SELECT MAX(" & columnName & ") As 'LastDate' FROM " & tableName
        Dim days As Integer? = CInt(IIf(IsNumeric(GetAppSetting("SyncDays")), GetAppSetting("SyncDays"), 0))
        Dim retVal As Date?

        If days > 0 Then retVal = DateTime.Now.AddDays(-1 * days) Else retVal = DateTime.Now.AddDays(-90)

        Using reader As IDataReader = DDA.SelectData(sql)
            If reader.Read Then
                retVal = CDate(ValueOrDefault(reader("LastDate"), retVal))
            End If
        End Using
        Return retVal
    End Function

    Public Function LastApplicationKillingTime() As DateTime
        Dim sql As String = "SELECT TOP 1 CreatedDateTime FROM SupportLogs_Monitoring ORDER BY LogID DESC"
        Dim retVal As DateTime = Nothing

        Using reader As IDataReader = DDA.SelectData(sql)
            If reader.Read Then
                retVal = CType(reader("CreatedDateTime"), DateTime)
            End If
        End Using
        If IsDate(retVal) Then Return retVal Else Return Nothing
    End Function

    Public Function SetApplicationStartTime() As Integer
        Dim dict As New Dictionary(Of String, Object)
        dict.Add("CreatedDateTime", System.DateTime.Now)
        dict.Add("Message", "Policella Synchronizer is going to restart now")

        Dim sql As String = "SELECT TOP 1 * FROM SupportLogs_Monitoring ORDER BY LogID DESC"
        Dim retVal As Integer = 0
        Using reader As IDataReader = DDA.SelectData(sql)
            If reader.Read Then
                retVal = DDA.Update("SupportLogs_Monitoring", dict, "LogID = " & CInt(ValueOrDefault(reader("LogID"), 0)), True)
            Else
                retVal = DDA.Insert("SupportLogs_Monitoring", dict)
            End If
        End Using

        Return retVal
    End Function

    Public Function IsReadyToKillSynchronizer() As Boolean
        Dim retVal As Boolean = False
        Try
            If LastApplicationKillingTime() <> Nothing Then
                Dim sql As String = "SELECT * FROM SupportLogs WHERE CreatedDate >= '" & LastApplicationKillingTime() & "' AND Category = 'trace' AND Message LIKE '%KillingProcess%'"

                Using reader As IDataReader = DDA.SelectData(sql)
                    If reader.Read Then
                        retVal = True
                        'SetApplicationStartTime()
                    End If
                End Using
            End If
        Catch ex As Exception
            Logger.WriteError("An error occurred during checking Is Ready to Kill Policella Synchronizer. Error Details " & ex.Message)
            Throw ex
        End Try
        Return retVal
    End Function

    Public Function IsReadyToKillSynchronizerForManualStop() As Boolean
        Dim retVal As Boolean = False
        Try

            Dim sql As String = "SELECT TOP 1 CreatedDateTime FROM SupportLogs_Monitoring ORDER BY LogID DESC"

            Using reader As IDataReader = DDA.SelectData(sql)
                If reader.Read Then

                    If CType(DateTime.Now.Subtract(CDate(reader("CreatedDateTime"))), TimeSpan).Hours >= 3 Then
                        retVal = True
                    End If

                    'SetApplicationStartTime()
                End If
            End Using

        Catch ex As Exception
            Logger.WriteError("An error occurred during checking Is Ready to Kill Policella Synchronizer. Error Details " & ex.Message)
            Throw ex
        End Try
        Return retVal
    End Function

    Public Function GetPageURLByPageID(PageID As Integer) As String
        Dim sql As String = "SELECT * FROM Menu WHERE MenuID = " & PageID
        Dim retVal As String = ""
        Using reader As IDataReader = DDA.SelectData(sql)
            If reader.Read Then
                retVal = ValueOrDefault(reader("Url"), "").ToString
                If retVal <> "" Then retVal = "~/admin/" & retVal
            End If
            reader.Close()
        End Using
        Return retVal
    End Function

    'Public ReadOnly Property UserID As Integer
    '    Get
    '        If Not HttpContext.Current.Items.Contains("UserID") Then
    '            If HttpContext.Current.User IsNot Nothing Then HttpContext.Current.Items("UserID") = BL.Users.GetUserIDByUsername(HttpContext.Current.User.Identity.Name)
    '        End If

    '        Return CInt(ValueOrDefault(HttpContext.Current.Items("UserID"), 0))
    '    End Get
    'End Property

    Public ReadOnly Property RoleID As Integer
        Get
            If Not HttpContext.Current.Items.Contains("RoleID") Then
                If HttpContext.Current.User IsNot Nothing Then HttpContext.Current.Items("RoleID") = BL.Users.GetRoleIDByUsername(HttpContext.Current.User.Identity.Name)
            End If

            Return CInt(ValueOrDefault(HttpContext.Current.Items("RoleID"), 0))
        End Get
    End Property

End Module
